package com.itcam.cm.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itcam.cm.feign.user.UserFeignClient;
import com.itcam.cm.model.entity.user.UserInfo;
import com.itcam.cm.util.ItcamAssert
;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.concurrent.CompletableFuture;

@Component
public class GuiguAuthFilter implements GlobalFilter, Ordered {

    @Lazy
    @Autowired
    UserFeignClient userFeignClient;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 统一鉴权
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        URI uri = request.getURI();
        String path = request.getPath().toString();
        boolean isPath = antPathMatcher.match("/api/**/auth/**", path);
        if(isPath){
            // 需要鉴权
            System.out.println(isPath);
            // 获取token
            String token = headers.get("token").get(0);
            ItcamAssert
.notNull(token,"token不能为空");

            // 调用user，检验token
            UserInfo userInfo = CompletableFuture.supplyAsync(()->{
                return userFeignClient.checkUserInfo(token);
            }).get();

            // 传递鉴权结果
            request.mutate().header("userJson", JSON.toJSONString(userInfo, SerializerFeature.BrowserSecure));
            exchange.mutate().request(request);

            System.out.println(userInfo);
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
